package cn.redragon.soa.service;

import brave.Tracer;
import cn.redragon.soa.common.dto.PageResultDTO;
import cn.redragon.soa.data.criteria.StockHistoryCriteria;
import cn.redragon.soa.data.dao.StockHistoryDao;
import cn.redragon.soa.data.entity.StockHistoryEntity;
import cn.redragon.soa.model.dto.stock.StockHistoryDTO;
import cn.redragon.soa.model.mapper.StockMapper;
import io.vavr.control.Try;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class StockHistoryService {

    private final StockHistoryDao stockHistoryDao;
    private final Tracer tracer;

    @Transactional(rollbackFor = Exception.class)
    public void save(String brand, List<StockHistoryDTO> historyDTOs) {
        historyDTOs.stream().forEach(i -> {
            StockHistoryEntity entity = StockMapper.INSTANCE.from(i);
            entity.setBrand(brand);
            entity.setTraceId(Try.of(() -> tracer.currentSpan().context().traceIdString()).getOrElse(() -> null));
            stockHistoryDao.save(entity);
        });
    }

    public PageResultDTO<StockHistoryDTO> list(StockHistoryCriteria criteria) {
        Page<StockHistoryEntity> pageResult = stockHistoryDao.findAll(criteria.toPredicate(), criteria.getPageable());
        return PageResultDTO.of(pageResult, StockMapper.INSTANCE::from);
    }
}
